<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

define('IN_ADMIN_COMPONENT_CONTROLLER', 'true');

require_once('includes/classes/Upload.php');
require_once('includes/functions/configuration_functions.php');

class EditProductComponent
{
	function EditProductComponent()
	{
	}

	function action(&$params, $action)
	{
		$this->message = array();
		$this->errorCode = 0;

		if ($action == 'InsertProduct') {
			$params['productId'] = 0;
			return $this->edit($params, $action);
		}
		else if ($action == 'UpdateProduct') 
			return $this->edit($params, $action);
		else if ($action == 'CopyAttributes') 
			return $this->copyAttributes($params, $action);
		else
			return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);
		$categoryId = (int)$params['categoryId'];
		$productId = (int)$params['productId'];
		$languageId = (int)$params['languageId'];

		if ($productId > 0)
		{
			$subParams['handle'] = $handle;
			$subParams['languageId'] = $languageId;
			$subParams['productId'] = $productId;
			$subParams['max_rows'] = 1;
			$subParams['return_details'] = true;
			$subParams['include_all_status'] = true;
			$subParams['return_download_if_no_filename'] = true;

			require_once('includes/components/ProductsSearchSubComponent.php');
			$subComponent = new ProductsSearchSubComponent();
			$value = $subComponent->query($subParams);
		}
		else 
		{
			$value{$handle . 'MetaData'}{'image_width_max'}= (int)SMALL_IMAGE_WIDTH;
			$value{$handle . 'MetaData'}{'image_height_max'}= (int)SMALL_IMAGE_HEIGHT;

			$value{$handle}{0}{'categories_id'}= $categoryId;
			$value{$handle}{0}{'status'}= false;
			$value{$handle}{0}{'qty_blocks'}= 1;
		}

		$value{$handle . 'MetaData'}{'number_of_price_breaks_max'}= (int)PRICE_BREAK_NOF_LEVELS;
		$value{$handle . 'MetaData'}{'download_enabled'}= returnBoolean(DOWNLOAD_ENABLED);
		$value{$handle . 'MetaData'}{'download_maxdays'}= (int)DOWNLOAD_MAX_DAYS;
		$value{$handle . 'MetaData'}{'download_maxcount'}= (int)DOWNLOAD_MAX_COUNT;

		$value{$handle}{0}{'error_code'}= $this->errorCode;
		$value{$handle}{0}{'message'}= $this->message;

		product_list(&$value, $handle, $languageId);
				
		return $value;
	}

	function edit(&$params, $action) 
	{
		$categoryId = (int)$params['categoryId'];
		$productId = (int)$params['productId'];
		$languageId = (int)$params['languageId'];

		$inventory = (int)$params['inventory'];
		$productModel = prepare_input($params['productModel']);
		$productPrice = (double)$params['productPrice'];
		$availableDate = (int)$params['availableDate'];
		$weight = (double)$params['weight'];
		$status = (int)$params['status'];
		$virtual = (int)$params['virtual'];
		$taxClassId = (int)$params['taxClassId'];
		$manufacturerId = (int)$params['manufacturerId'];
		$quantityBlocks = (int)$params['quantityBlocks'];
		$imageWidthMax = (int)$params['imageWidthMax'];
		$imageHeightMax = (int)$params['imageHeightMax'];
		$image0 = prepare_input($params['image-0']);
		$image1 = prepare_input($params['image-1']);
		$image2 = prepare_input($params['image-2']);
		$image3 = prepare_input($params['image-3']);
		$image4 = prepare_input($params['image-4']);
		$image5 = prepare_input($params['image-5']);
		$image6 = prepare_input($params['image-6']);

		$productName = trusted_prepare_input($params['productName']);
		$description = trusted_prepare_input($params['description']);
		$url = prepare_input($params['url']);

		$discountCategoryId = (int)$params['discountCategoryId'];

		$numPriceBreaks = (int)PRICE_BREAK_NOF_LEVELS;
		$priceBreaks = array();
		$i = 0;
		$ipb = 0;
		while ($i <= $numPriceBreaks)
		{
			$priceBreakPrice = (double)$params['priceBreakPrice-'.$i];
			$priceBreakQuantity = (int)$params['priceBreakQuantity-'.$i];
			
			if ($priceBreakQuantity > 0 && $priceBreakPrice > 0.0) {
				$priceBreaks{$ipb}{'price'}= $priceBreakPrice;
				$priceBreaks{$ipb}{'quantity'} = $priceBreakQuantity;
				$ipb++;
			}		
			$i++;
		}
		
		$downloadEnabled = returnBoolean(DOWNLOAD_ENABLED);
		$attributes = array();
		$i = 0;
		$iatt = 0;
		while (true)
		{
			$optionNameId = (int)$params['optionNameId-'.$i];
			if ($optionNameId == 0) break;

			if ($optionNameId > 0)
			{
				$attributes{$iatt}{'paId'} = (int)$params['paId-'.$i];
				$attributes{$iatt}{'nameId'} = $optionNameId;
				$attributes{$iatt}{'valueId'} = (int)$params['optionValueId-'.$i];
				$attributes{$iatt}{'prefix'} = prepare_input($params['prefix-'.$i]);
				$attributes{$iatt}{'price'} = (double)$params['optionPrice-'.$i];
				$attributes{$iatt}{'sortOrder'} = (int)$params['sortOrder-'.$i];
				if ($downloadEnabled) {
					$attributes{$iatt}{'filename'} = prepare_input($params['filename-'.$i]);
					$attributes{$iatt}{'maxdays'} = (int)$params['maxdays-'.$i];
					$attributes{$iatt}{'maxcount'} = (int)$params['maxcount-'.$i];
				}
				$iatt++;
			}
			$i++;
			if ($i > 10000) break;
		}

		//Products table
		$sql_data_array = array();
		$sqlAction = 'insert';
		$where = '';
		if ($action == 'UpdateProduct') {
			$sqlAction = 'update';
			$where = 'products_id=' . $productId;
		}
		else {
			$sql_data_array['products_date_added'] = 'now()';
			$sql_data_array['products_ordered'] = 0;
		}
		
		$sql_data_array['products_last_modified'] = 'now()';
		$sql_data_array['products_quantity'] = $inventory;
		$sql_data_array['products_model'] = $productModel;
		$sql_data_array['products_price'] = $productPrice;
		$sql_data_array['products_weight'] = $weight;
		$sql_data_array['products_status'] = $status;
		$sql_data_array['products_virtual'] = $virtual;
		$sql_data_array['products_tax_class_id'] = $taxClassId;
		$sql_data_array['manufacturers_id'] = $manufacturerId;
		$sql_data_array['products_qty_blocks'] = $quantityBlocks;
		$sql_data_array['products_image_max_width'] = $imageWidthMax;
		$sql_data_array['products_image_max_height'] = $imageHeightMax;

        	$image = new Upload($image0, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['products_image'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image1, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_1'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image2, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_2'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image3, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_3'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image4, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_4'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image5, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_5'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}

        	$image = new Upload($image6, DIR_FS_CATALOG_IMAGES . 'products/', false);
		if ($image->parse() && $image->save()) {
			$sql_data_array['product_image_6'] = $image->filename;
		}
		else {
			if ($image->error_code < 0) {
				$this->errorCode = $image->error_code;
				$this->message[] = $image->message;
			}
		}
		db_perform(TABLE_PRODUCTS, $sql_data_array, $sqlAction, $where);

		//Product Descriptions table and Available Date on Products table
		$sql_data_array = array();
		$where = '';
		if ($sqlAction == 'insert')
		{
			$productId = mysql_insert_id();
			$sql_data_array['products_id'] = $productId;
			$sql_data_array['language_id'] = $languageId;
			$sql_data_array['products_viewed'] = 0;
		}
		else
		{
			$where = 'products_id=' . $productId . ' and language_id=' . $languageId;
		}

		if ($availableDate > 0) {
			$availableDate_sec = (int)$availableDate/1000.00;
			$sql = 'update ' . TABLE_PRODUCTS . ' set products_date_available = \'' . date('Y-m-d',$availableDate_sec) . '\' where products_id=' . $productId;
			mysql_query($sql) or die(mysql_error());
		}
		else {
			$sql = 'update ' . TABLE_PRODUCTS . ' set products_date_available = null where products_id=' . $productId;
			mysql_query($sql) or die(mysql_error());
		}

		$sql_data_array['products_name'] = $productName;
		$sql_data_array['products_description'] = $description;
		$sql_data_array['products_url'] = $url;
		db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array, $sqlAction, $where);

		//Product to Categories table
		if ($sqlAction == 'insert')
		{
			$sql_data_array = array();
			$sql_data_array['products_id'] = $productId;
			$sql_data_array['categories_id'] = $categoryId;
			db_perform(TABLE_PRODUCTS_TO_CATEGORIES, $sql_data_array, $sqlAction, $where);
		}

		//Products to Discount Categories table
		if ($sqlAction == 'update')
		{
			$sql = 'delete from ' . TABLE_PRODUCTS_TO_DISCOUNT_CATEGORIES . ' where products_id=' . $productId;
			mysql_query($sql) or die(mysql_error());
		}
		if ($discountCategoryId > 0) {
			$sql_data_array = array();
			$sql_data_array['products_id'] = $productId;
			$sql_data_array['discount_categories_id'] = $discountCategoryId;
			db_perform(TABLE_PRODUCTS_TO_DISCOUNT_CATEGORIES, $sql_data_array, 'insert', '');
		}

		//Products Price Break table
		$szPriceBreaks = count($priceBreaks);

		$i = 0;
		if ($sqlAction == 'update')
		{
			$sqlQuery = 'select products_price_break_id, products_price, products_qty ' .
			'from  ' . TABLE_PRODUCTS_PRICE_BREAK . ' ' .
			'where products_id = \'' . $productId . '\' ' .
			'order by products_qty';
	
			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			while($row = mysql_fetch_array($dataReturned))
			{
				$priceBreakId = (int)$row['products_price_break_id'];
				$priceBreakPriceTable = (double)$row['products_price'];
				$priceBreakQuantityTable = (int)$row['products_qty'];
				if ($i < $szPriceBreaks) {
					$priceBreakPrice = $priceBreaks[$i]['price'];
					$priceBreakQuantity = $priceBreaks[$i]['quantity'];

					if ($priceBreakPrice != $priceBreakPriceTable || $priceBreakQuantity != $priceBreakPriceQuantity) {
						$sql_data_array = array();
						$sql_data_array['products_id'] = $productId;
						$sql_data_array['products_price'] = $priceBreakPrice;
						$sql_data_array['products_qty'] = $priceBreakQuantity;
						db_perform(TABLE_PRODUCTS_PRICE_BREAK, $sql_data_array, 'update', 'products_price_break_id=' . $priceBreakId);
					}
				}
				else {
					$sql = 'delete from  ' . TABLE_PRODUCTS_PRICE_BREAK . ' where products_price_break_id=' . $priceBreakId;
					mysql_query($sql) or die(mysql_error());
				}
				$i++;
			}
		}
		if ($szPriceBreaks > $i)
		{
			while ($i < $szPriceBreaks)
			{
				$priceBreakPrice = $priceBreaks[$i]['price'];
				$priceBreakQuantity = $priceBreaks[$i]['quantity'];
				$sql_data_array = array();
				$sql_data_array['products_id'] = $productId;
				$sql_data_array['products_price'] = $priceBreaks[$i]['price'];
				$sql_data_array['products_qty'] = $priceBreaks[$i]['quantity'];
				db_perform(TABLE_PRODUCTS_PRICE_BREAK, $sql_data_array, 'insert', '');
				$i++;
			}
		}

		//Products Attributes table

		$i = 0;
		if ($sqlAction == 'update')
		{
			$sqlQuery = 'select pa.products_attributes_id ' .
			'from ' . TABLE_PRODUCTS_OPTIONS . ' po, ' . TABLE_PRODUCTS_OPTIONS_VALUES . ' pov, ' . TABLE_PRODUCTS_ATTRIBUTES . ' pa ' .
			'where pa.products_id = \'' . $productId . '\' ' .
			'and pa.options_id = po.products_options_id and po.language_id = \'' . $languageId . '\' ' .
			'and pa.options_values_id = pov.products_options_values_id and pov.language_id = \'' . $languageId . '\' ' .
			'order by pa.products_attributes_id';

			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			while($row = mysql_fetch_array($dataReturned))
			{
				$current_paId = (int)$row['products_attributes_id'];
				$match = false;
				reset($attributes);
				$iatt = 0;
				while (list(,$attribute) = each($attributes))
				{
					if ($current_paId == $attribute['paId']) {
						$sql_data_array = array();
						$sql_data_array['products_id'] = $productId;
						$sql_data_array['options_id'] = $attribute['nameId'];
						$sql_data_array['options_values_id'] = $attribute['valueId'];
						$sql_data_array['options_values_price'] = $attribute['price'];
						$sql_data_array['price_prefix'] = $attribute['prefix'];
						$sql_data_array['attribute_sort'] = $attribute['sortOrder'];
						db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql_data_array, 'update', 'products_attributes_id='.$current_paId);
						if ($downloadEnabled) {
							if ($attribute['filename'] == null || strlen($attribute['filename']) == 0) {
								$sql = 'delete from  ' . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . ' where products_attributes_id='.$current_paId;
								mysql_query($sql) or die(mysql_error());
							}
							else {
								$sqlAction1 = 'insert';
								$where = '';
								$sqlQuery1 = 'select products_attributes_id from ' . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . ' where products_attributes_id='.$current_paId;
								$dataReturned1 = mysql_query($sqlQuery1) or die(mysql_error());
								while($row1 = mysql_fetch_array($dataReturned1))
								{
									$sqlAction1 = 'update';
									$where = 'products_attributes_id='.$current_paId;
									break;
								}
								$sql_data_array = array();
								$sql_data_array['products_attributes_id'] = $current_paId;
								$sql_data_array['products_attributes_filename'] = $attribute['filename'];
								$sql_data_array['products_attributes_maxdays'] = $attribute['maxdays'];
								$sql_data_array['products_attributes_maxcount'] = $attribute['maxcount'];
								db_perform(TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD, $sql_data_array, $sqlAction1, $where);

							}
						}
						$attributes[$iatt++]['paId'] = -1;
						$match = true;
						break;
					}
					$iatt++;
				}
								
				if (!$match) {
					$sql = 'delete from  ' . TABLE_PRODUCTS_ATTRIBUTES . ' where products_attributes_id='.$current_paId;
					mysql_query($sql) or die(mysql_error());
					if ($downloadEnabled) {
						$sql = 'delete from  ' . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . ' where products_attributes_id='.$current_paId;
						mysql_query($sql) or die(mysql_error());
					}
				}
			}
		}
		reset($attributes);
		while (list(,$attribute) = each($attributes))
		{
			if ($attribute['paId'] > -1) {
				$sql_data_array = array();
				$sql_data_array['products_id'] = $productId;
				$sql_data_array['options_id'] = $attribute['nameId'];
				$sql_data_array['options_values_id'] = $attribute['valueId'];
				$sql_data_array['options_values_price'] = $attribute['price'];
				$sql_data_array['price_prefix'] = $attribute['prefix'];
				$sql_data_array['attribute_sort'] = $attribute['sortOrder'];
				db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql_data_array, 'insert', '');
				if ($downloadEnabled && $attribute['filename'] != null && strlen($attribute['filename']) > 0) {
					$paId = mysql_insert_id();
					$sql_data_array = array();
					$sql_data_array['products_attributes_id'] = $paId;
					$sql_data_array['products_attributes_filename'] = $attribute['filename'];
					$sql_data_array['products_attributes_maxdays'] = $attribute['maxdays'];
					$sql_data_array['products_attributes_maxcount'] = $attribute['maxcount'];
					db_perform(TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD, $sql_data_array, 'insert', '');
				}
			}			
		}

		remove_cache($languageId . '_' . $productId, 'AlsoPurchasedComponent');
		clean_cache('BestSellersComponent');
		clean_cache('CategoriesComponent');
		clean_cache('NewProductsComponent');
		remove_cache($languageId . '_' . $productId . '_true', 'ProductComponent');
		remove_cache($languageId . '_' . $productId . '_false', 'ProductComponent');
		remove_cache($languageId . '_' . $productId, 'ProductXSellComponent');
		clean_cache('RandomReviewComponent');
		clean_cache('SpecialsComponent');
		clean_cache('UpcomingProductsComponent');
		clean_cache('WhatsNewComponent');

		$params['productId'] = $productId;
		return $this->query($params);
	}

	function copyAttributes(&$params, $action) 
	{
		$handle = get_class($this);
		$categoryId = (int)$params['categoryId'];
		$copyProductId = (int)$params['copyProductId'];
		$productId = (int)$params['productId'];
		$languageId = (int)$params['languageId'];

		$downloadEnabled = returnBoolean(DOWNLOAD_ENABLED);

		if ($copyProductId > 0)
		{
			$value = $this->query($params);
			$value{$handle}{0}{'attributes'} = array();

			$sqlQuery = 'select  pa.products_attributes_id, pa.options_id, po.products_options_name, pa.options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix, pa.attribute_sort';
				
			if ($downloadEnabled) {
				$sqlQuery .= ', pad.products_attributes_filename, pad.products_attributes_maxdays, pad.products_attributes_maxcount';
			}

			$sqlQuery .= ' from ' . TABLE_PRODUCTS_OPTIONS . ' po, ' . TABLE_PRODUCTS_OPTIONS_VALUES . ' pov, ' . TABLE_PRODUCTS_ATTRIBUTES . ' pa '; 

			if ($downloadEnabled) {
				$sqlQuery .= 'left join ' . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . ' pad on (pa.products_attributes_id = pad.products_attributes_id) ';
			}

			$sqlQuery .= 'where pa.products_id = \'' . $copyProductId . '\' ' .
			'and pa.options_id = po.products_options_id and po.language_id = \'' . $languageId . '\' ' .
			'and pa.options_values_id = pov.products_options_values_id and pov.language_id = \'' . $languageId . '\' ' .
			'order by products_options_name, pa.attribute_sort, pov.products_options_values_name';

			$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
			$i = 0;
			while($row = mysql_fetch_array($dataReturned))
			{
				$value{$handle}{0}{'attributes'}{$i}{'row_id'}= (int)$row['products_attributes_id'];
				$value{$handle}{0}{'attributes'}{$i}{'product_id'}= $productId;
				$value{$handle}{0}{'attributes'}{$i}{'id'}= (int)$row['options_id'];
				$value{$handle}{0}{'attributes'}{$i}{'name'}= $row['products_options_name'];
				$value{$handle}{0}{'attributes'}{$i}{'values_id'}= (int)$row['options_values_id'];
				$value{$handle}{0}{'attributes'}{$i}{'values_name'}= $row['products_options_values_name'] . $values_name_extension;
				$value{$handle}{0}{'attributes'}{$i}{'values_price'}= (double)$row['options_values_price'];
				$value{$handle}{0}{'attributes'}{$i}{'values_price_prefix'}= $row['price_prefix'];

				if ($downloadEnabled) {
					$value{$handle}{0}{'attributes'}{$i}{'filename'}= $row['products_attributes_filename'];
					$value{$handle}{0}{'attributes'}{$i}{'maxdays'}= (int)$row['products_attributes_maxdays'];
					$value{$handle}{0}{'attributes'}{$i}{'maxcount'}= (int)$row['products_attributes_maxcount'];
				}
				$i++;
			}
			if ($productId > 0) {
				remove_cache($languageId . '_' . $productId . '_true', 'ProductComponent');
				remove_cache($languageId . '_' . $productId . '_false', 'ProductComponent');
			}
			return $value;	
		}
		return $this->query($params);
	}
}
?>

